﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Collections.Specialized;
using DynamicChart.Data;
using DynamicChart.Web.Models;
using SmartSpace;

namespace DynamicChart.Web
{
    /// <summary>
    /// Summary description for DemoService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class DynamicChartWebService : System.Web.Services.WebService
    {
        [WebMethod]
        public SingleResult<ChartData> GetData(string module, DateRange dateRange, string parametersString)
        {
            QueryParameter parameter = new QueryParameter();
            try
            {
                NameValueCollection nameValues = HttpUtility.ParseQueryString(parametersString.Replace(',', '&'));
                foreach (var item in nameValues.AllKeys)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        parameter[item] = nameValues[item];
                    }
                }

            }
            catch (Exception ex)
            {
                return new SingleResult<ChartData>(false,  ex.Message + ex.StackTrace, null);
            }

            IChartDataQuery query = DynamicChartFactory.GetQuery(module);

            if (query != null)
            {
                try
                {
                    return new SingleResult<ChartData>(true, "获取成功!", query.GetData(dateRange, parameter));
                }
                catch(Exception ex)
                {
                    return new SingleResult<ChartData>(false, ex.Message + ex.StackTrace, null);
                }
            }
            return new SingleResult<ChartData>(false, string.Format("获取失败,名为{0}的query对象无法找到!", module), null);
        }

        [WebMethod]
        public ChartPackage GetPackage(string module, DateRange dateRange, string parameterString)
        {
            IChartBuilder builder = DynamicChartFactory.GetBuilder(module);

            if (builder != null)
            {
                return builder.Build(dateRange, parameterString);
            }
            return null;
        }
    }
}
